#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import logging
import time
from .cloud_api import CloudAPI

class WorkspaceManager:
    """工作空间管理类"""
    
    @staticmethod
    def list_workspaces(api: CloudAPI):
        """
        列出所有工作空间信息
        
        Args:
            api: CloudAPI实例
        """
        try:
            workspaces = api.get_workspaces()
            print("\n可用的工作空间列表:")
            print("-" * 60)
            print(f"{'SpaceKey':<20} {'名称':<20} {'状态':<10}")
            print("-" * 60)
            for workspace in workspaces:
                print(f"{workspace.SpaceKey:<20} {workspace.Name:<20} {workspace.Status:<10}")
            print("-" * 60)
            print("\n请将需要监控的工作空间的SpaceKey配置到config.yaml文件的workspace.space_key中")
            
        except Exception as e:
            logging.error(f"Failed to list workspaces: {e}")
    
    def __init__(self, api: CloudAPI, target_workspace: str, check_interval: int = 300):
        """
        初始化工作空间管理器
        
        Args:
            api: CloudAPI实例
            target_workspace: 目标工作空间标识
            check_interval: 检查间隔(秒)，默认5分钟
        """
        self.logger = logging.getLogger(__name__)
        self.api = api
        self.target_workspace = target_workspace
        self.check_interval = check_interval
        
    def check_workspace_status(self):
        """
        检查工作空间状态
        
        Returns:
            bool: 工作空间是否在运行
        """
        try:
            workspaces = self.api.get_workspaces()
            for workspace in workspaces:
                if workspace.SpaceKey == self.target_workspace:
                    is_running = workspace.Status == "Running"
                    self.logger.info(f"Workspace {self.target_workspace} status: {workspace.Status}")
                    return is_running
                    
            self.logger.warning(f"Target workspace {self.target_workspace} not found")
            return False
            
        except Exception as e:
            self.logger.error(f"Failed to check workspace status: {e}")
            return False
            
    def ensure_workspace_running(self):
        """
        确保工作空间处于运行状态
        """
        if not self.check_workspace_status():
            self.logger.info(f"Starting workspace {self.target_workspace}")
            self.api.run_workspace(self.target_workspace)
            
    def run(self):
        """
        运行管理器主循环
        """
        self.logger.info("Workspace manager started")
        
        while True:
            try:
                self.ensure_workspace_running()
                time.sleep(self.check_interval)
                
            except KeyboardInterrupt:
                self.logger.info("Workspace manager stopped")
                break
                
            except Exception as e:
                self.logger.error(f"Error in main loop: {e}")
                time.sleep(self.check_interval) 